<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/31
 * Time: 15:23
 */

namespace App\Rep;


use App\Models\Customer;
use App\Models\FinishProduct;
use App\Models\ModelNumber;
use App\Models\Order;
use App\Models\SemiFinishProduct;
use Illuminate\Support\Facades\DB;

class IndexRep
{

    public function getIndexHeaderDataRep($params){
        return [
            'this_year_order_num'=>$this->getThisYearsOrderNumber(),//获取今年订单量
            'pending_acceptance_order_nunber'=>$this->getPendingAcceptanceOrderNunber(),//获取待待收尾款订单数
            'shipped_order_number'=>$this->getShippedOrderNumber(),//获取已发货订单
            'unfilled_orders_number'=>$this->getUnfilledOrdersNumber(),//获取未发货订单
            'qty_backordered'=>$this->getQtyBackordered(),//获取备货量
            'quantity_of_orders_in_production'=>$this->getQuantityOfOrdersInProduction($params),//获取生产中订单
            'to_be_reviewed'=>$this->getToBeReviewed()
        ];

    }

    /**
     * 获取待审核数据
     */
    public function getToBeReviewed(){
        return Order::where('status','<>',1)->where('is_del',2)->count();
    }

    /**
     * 获取近30天数据
     */
    public function getThirtyDayOrderNumberRep(){
        $xAxis = [];
        for ($i = 30; $i >= 0; $i--) {
            $xAxis[] = date('Y-m-d', strtotime("-$i days"));
        }
        //p($xAxis);
        $yAxis = [];
        foreach($xAxis as $k=>$v){
            $start_time = $v." 00:00:00";
            $end_time = $v." 23:59:59";
            $yAxis[] = Order::whereBetween('order_date',[$start_time,$end_time])->where('status',1)->where('is_del',2)->count();
        }
        return ['code'=>0,'data'=>['xAxis'=>$xAxis,'yAxis'=>$yAxis],'msg'=>'success'];
    }

    /**
     * 年度下单TOP10客户
     */
    public function getTOP10CustomerRep(){
        $data = [];
        $year = date("Y");
        $start_time = $year."-01-01";
        $end_time = $year."-12-31";
        $list = Order::select(DB::raw('count(*) as order_count, customer_id'))
            ->where('is_del',2)
            ->whereBetween('order_date',[$start_time,$end_time])->where('status',1)->where('customer_id','<>',0)
            ->with('customer')
            ->groupBy('customer_id')
            ->offset(0)->limit(10)
            ->get()->toArray();

        $arr = array_sort($list,'order_count','desc');
        foreach($arr as $k=>$v){
            $data['xAxis'][] = $v['order_count'];
            $data['yAxis'][] = $v['customer']['customer_name'];
        }
        return ['code'=>0,'data'=>$data,'msg'=>'success'];
    }


    /**
     * 年度产品
     */
    public function getAnnualProductOrderNumberRep(){
        $data = [];
        $year = date("Y");
        $start_time = $year."-01-01";
        $end_time = $year."-12-31";
        $list = Order::select(DB::raw('count(*) as order_count, product_id'))
            ->where('is_del',2)
            ->whereBetween('order_date',[$start_time,$end_time])->where('status',1)
            ->with('product')
            ->groupBy('product_id')
            ->get()->toArray();
        $arr = array_sort($list,'order_count','desc');
        foreach($arr as $k=>$v){
            $data['yAxis'][] = $v['order_count'];
            $data['xAxis'][] = $v['product']['product_name'];
        }
        return ['code'=>0,'data'=>$data,'msg'=>'success'];
    }


    /**
     * 近6个月订单量
     */
    public function getNearlySexMonthsOrderNumberRep(){
        $xAxis = [];
        for ($i = 6; $i >= 0; $i--) {
            $xAxis[] = date('Y-m', strtotime("-$i month"));
        }
        //p($xAxis);
        $yAxis = [];
        foreach($xAxis as $k=>$v){
            $start_time = $v."-01 00:00:00";
            $end_time = date("Y-m-t 23:59:59", strtotime($start_time));
            $yAxis[] = Order::whereBetween('order_date',[$start_time,$end_time])->where('is_del',2)->where('status',1)->count();
        }
        return ['code'=>0,'data'=>['xAxis'=>$xAxis,'yAxis'=>$yAxis],'msg'=>'success'];


    }






    /**
     * 获取今年订单量
     */
    public function getThisYearsOrderNumber(){
        $year = date("Y");
        $start_time = $year."-01-01";
        $end_time = $year."-12-31";
        $count = Order::whereBetween('order_date',[$start_time,$end_time])->where('is_del',2)->where('status',1)->count();
        return $count;
    }


    /**
     * 获取待验收订单（半成品）
     * 获取待收尾款订单
     */
    public function getPendingAcceptanceOrderNunber(){
        $count = SemiFinishProduct::where('is_del',2)->count();
        //$count = DB::table('order_shafa')->where('is_residual_payment',2)->count();

        return $count;
    }

    /**
     * 获取已发货订单
     */
   public function getShippedOrderNumber(){
        $year = date("Y");
        $start_time = $year."-01-01";
        $end_time = $year."-12-31";
        return FinishProduct::where('logistics_status',3)
            ->where('is_stock_up',2)
            ->whereBetween('warehouse_entry_time',[$start_time,$end_time])
            ->count();
    }

    /**
     * 获取未发货订单
     */
    public function getUnfilledOrdersNumber(){
//        $year = date("Y");
//        $start_time = $year."-01-01";
//        $end_time = $year."-12-31";
        return FinishProduct::where('logistics_status','<>',3)
            ->where('is_stock_up',2)
            //->whereBetween('warehouse_entry_time',[$start_time,$end_time])
            ->count();
    }


    /**
     * 获取备货量
     */
    public function getQtyBackordered(){
//        $year = date("Y");
//        $start_time = $year."-01-01";
//        $end_time = $year."-12-31";
        return FinishProduct::where('is_stock_up',1)
            //->whereBetween('warehouse_entry_time',[$start_time,$end_time])
            ->count();
    }

    /**
     * 获取生产中订单
     */
    public function getQuantityOfOrdersInProduction($params){
        //$params = [];
        return Order::Schedule($params)->where('is_del',2)->where('is_replenishment',2)->count();
    }


    /**
     * 按型号统计订单
     * @return void
     */
    public function getModelNumberTabelRep($params){

        $list = ModelNumber::where('is_del',2)
            ->where(function($q)use($params){
                if(!empty($params['model_number_id'])){
                    $q->where('id',$params['model_number_id']);
                }
            })
            ->select('id','model_number')->get()->toArray();
        foreach($list as $k=>$v){
            //型号筛选订单数
            $order_num = Order::where('is_del',2)->where(function($q)use($params){
                $start_time = $params['start_time']??date("Y-01-01");
                $end_time = $params['end_time']??date("Y-m-d");
                $q->whereBetween('order_date',[$start_time,$end_time]);
            })
                ->where('model_number_id',$v['id'])
                ->count();
            //金额
            $order_receivables = Order::where('is_del',2)->where(function($q)use($params){
                $start_time = $params['start_time']??date("Y-01-01");
                $end_time = $params['end_time']??date("Y-m-d");
                $q->whereBetween('order_date',[$start_time,$end_time]);
            })
                ->where('model_number_id',$v['id'])
                ->sum('receivables');
            $list[$k]['order_num'] = $order_num;
            $list[$k]['order_receivables'] = $order_receivables;
        }

        $order_num_total = Order::where('is_del',2)->where(function($q)use($params){
            $start_time = $params['start_time']??date("Y-01-01");
            $end_time = $params['end_time']??date("Y-m-d");
            $q->whereBetween('order_date',[$start_time,$end_time]);
            if(!empty($params['model_number_id'])){
                $q->where('model_number_id',$params['model_number_id']);
            }
        })
            ->count();
        //金额
        $order_receivables_total = Order::where('is_del',2)->where(function($q)use($params){
            $start_time = $params['start_time']??date("Y-01-01");
            $end_time = $params['end_time']??date("Y-m-d");
            $q->whereBetween('order_date',[$start_time,$end_time]);
            if(!empty($params['model_number_id'])){
                $q->where('model_number_id',$params['model_number_id']);
            }
        })
            ->sum('receivables');

        $data = ['list'=>$list,'total'=>['order_num_total'=>$order_num_total,'order_receivables_total'=>$order_receivables_total]];
        return ['code'=>0,'data'=>$data,'msg'=>'success'];
    }

    /**
     * 客户订单统计
     * @param $params
     * @return void
     */
    public function getCustomerTableRep($params){
        $list = Customer::where('is_del',2)
            ->where(function($q)use($params){
                if(!empty($params['customer_name'])){
                    $q->where('customer_name','like','%'.$params['customer_name'].'%');
                }
            })
            ->select('id','customer_name')->get()->toArray();
        foreach($list as $k=>$v){
            //型号筛选订单数
            $order_num = Order::where('is_del',2)->where(function($q)use($params){
                $start_time = $params['start_time']??date("Y-01-01");
                $end_time = $params['end_time']??date("Y-m-d");
                $q->whereBetween('order_date',[$start_time,$end_time]);
            })
                ->where('customer_id',$v['id'])
                ->count();
            //金额
            $order_receivables = Order::where('is_del',2)->where(function($q)use($params){
                $start_time = $params['start_time']??date("Y-01-01");
                $end_time = $params['end_time']??date("Y-m-d");
                $q->whereBetween('order_date',[$start_time,$end_time]);

            })
                ->where('customer_id',$v['id'])
                ->sum('receivables');
            //最后一次订单时间
            $last_order = Order::where('is_del',2)->where('customer_id',$v['id'])
                ->orderBy('order_date','desc')->first();
            if($last_order){
                $last_order_date = $last_order->order_date;
            }

            $list[$k]['order_num'] = $order_num;
            $list[$k]['order_receivables'] = $order_receivables;
            $list[$k]['last_order_date'] = $last_order_date??'';
        }

        $order_num_total = Order::where('is_del',2)->where(function($q)use($params){
            $start_time = $params['start_time']??date("Y-01-01");
            $end_time = $params['end_time']??date("Y-m-d");
            $q->whereBetween('order_date',[$start_time,$end_time]);
            if(!empty($params['customer_name'])){
                $customer_id_arr = Customer::where('customer_name','like','%'.$params['customer_name'].'%')->pluck('id')->toArray();
                $q->whereIn('customer_id',$customer_id_arr);
            }

        })
            ->count();
        //金额
        $order_receivables_total = Order::where('is_del',2)->where(function($q)use($params){
            $start_time = $params['start_time']??date("Y-01-01");
            $end_time = $params['end_time']??date("Y-m-d");
            $q->whereBetween('order_date',[$start_time,$end_time]);
            if(!empty($params['customer_name'])){
                $customer_id_arr = Customer::where('customer_name','like','%'.$params['customer_name'].'%')->pluck('id')->toArray();
                $q->whereIn('customer_id',$customer_id_arr);
            }
        })
            ->sum('receivables');

        $lists = array_values(array_sort($list,'order_num','desc'));
        //p($lists);
        $data = ['list'=>$lists,'total'=>['order_num_total'=>$order_num_total,'order_receivables_total'=>$order_receivables_total]];
        return ['code'=>0,'data'=>$data,'msg'=>'success'];
    }


}
